package cn.chenchao.eshop.common.dao.imp;

import cn.chenchao.eshop.common.dao.IDataAccess;
import cn.chenchao.eshop.common.entity.Entity;
import cn.chenchao.eshop.goods.entity.Goods;
import org.apache.commons.io.FileUtils;
import util.JsonUtil;

import java.io.File;
import java.util.List;

/**
 * @encoding : UTF-8
 * @Time : 2020/11/22 19:25
 * @Author : Chen Chao
 * @File : eshop.cn.chenchao.eshop.common.dao.imp.TextAccess.java
 * @Software : IntelliJ IDEA
 * @since : 1.8
 */
public class TextAccess implements IDataAccess {
    public static final String COMMA=",";
    @Override
    public <T> List<T> getList(Class<T> tClass) throws Exception {
        /*1获取该类对象对应的文件*/
        File file = TextAccess.getFile( tClass);
        /*2从文件中读取字符串*/
        List<T> ts = null;
        if (file.exists()) {
            String json = FileUtils.readFileToString(file, "UTF-8");
            /*3.从字符串中获取对象列表*/
            if(json.startsWith(COMMA)){
                json=json.substring(1);
            }
            ts = JsonUtil.jsonArray2List("["+json+"]", tClass);
        }
        return ts;
    }

    /**
     * 把对象写入文件
     * @param t  实例对象
     * @param <T>  实例对象对应的类
     * @throws Exception 抛出异常
     */
    @Override
    public <T> void insert2List(T t) throws Exception {
        String s = JsonUtil.entity2Json(t);
        FileUtils.writeStringToFile(TextAccess.getFile(t.getClass()),s+COMMA,"UTF-8",true);
    }

    /**
     * 根据类对象获取对应的文件
     * @param <T> 类
     * @param tClass 类对象
     * @return 类对象获取对应的文件
     */
    public static <T> File getFile(Class<T> tClass){
        /*1.根据类名拼接字符串*/
        String fileName = "db_" + tClass.getSimpleName().toLowerCase() + ".txt";
        String path = "common/src/cn/chenchao/eshop/common/db";
        /*2.根据路径名创建抽象文件对象*/
        return new File(path, fileName);
    }
    public static void main(String[] args) throws Exception {
        TextAccess textAccess = new TextAccess();
        textAccess.getList(Entity.class);


        Goods goods = new Goods("苹果", 100, 100);
        try {
            textAccess.insert2List(goods);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
